const path = require('path');
const fs = require('fs');
const db = require("./sqlitedb.js");

const mypath = "http://localhost:3000"
//写入新闻列表的初始信息
exports.setnewsinfo = (req,res)=>{
    let obj = req.body;
    let title = obj.title;
    let time = obj.time;
    let zhaiyao = obj.zhaiyao;
    let txturl = obj.txturl;   
    let first_imgurl = obj.first_imgurl;
    db.setinfo(`INSERT INTO NEWINFO(TITLE,ADD_TIME,ZHAIYAO,CLICK,TXT_URL,FIRST_IMGURL) VALUES('${title}','${time}','${zhaiyao}','0','${txturl}','${first_imgurl}')`).then((data)=>{
        res.header('Access-Control-Allow-Origin', '*');
        console.log(data);
        res.json({
            status:0
        });
    },(err)=>{
        res.header('Access-Control-Allow-Origin', '*');
        console.log(err)
        res.json(err);
    })
}
//获取当前id的点击数量
function getclick(id){
    return new Promise((res,rej)=>{
        db.getinfo(`SELECT CLICK FROM NEWINFO WHERE ID = '${id}'`).then((data)=>{
            res(data[0].CLICK);               
        },(err)=>{
            rej('error') ;
        })
    })
    
}
//更新当前的点击数
exports.addclicktime = (req,res)=>{
    let id = req.params.id;
    getclick(id).then((data)=>{
        let click = parseInt(data)+1;
        db.setinfo(`UPDATE NEWINFO SET CLICK = '${click}' WHERE ID = '${id}'`).then((data)=>{
            res.header('Access-Control-Allow-Origin', '*');
            res.json({status:0});
        },(err)=>{
            res.header('Access-Control-Allow-Origin', '*');
            res.json({status:1});
        })
    })
    
}
// exports.addclicktime = (req,res)=>{
//     let id = req.params.id;
//     let click = getclick(id)+1;
//     db.setinfo(`UPDATE NEWINFO SET ID = '${click}' WHERE ID = '${id}'`).then((data)=>{
//         res.header("Access-Control-Allow-Origin");
//         res.json(data);
//     },(err)=>{
//         res.header("Access-Control-Allow-Origin");
//         res.json(err);
//     })
// }
//上传文字信息
exports.uploadtxt = (req,res)=>{
    let obj = req.body;
    let title = obj.title;//标题
    let content = obj.content;//内容
    let id = (new Date().getTime())+parseInt(Math.random()*3647)+parseInt(Math.random()*8952)
    let filename =id +".txt";
    let txtpath = `${mypath}/news/info/${filename}`;
    fs.writeFile(path.join(__dirname,`../public/news/info/${filename}`),content,'utf8',(err)=>{
        if(err){
            res.header("Access-Control-Allow-Origin","*");
            res.json(err);
        }else{
            res.header("Access-Control-Allow-Origin","*");
            res.json({
                status:0,
                message:[{'name':filename,'id':id}]
                
            })
        }
    })
}
//图片分享的数据上传数据库
exports.uploadsqlimginfo = (req,res)=>{
    let obj = req.body;
    let id = obj.id;
    let type = obj.type;
    let title = obj.title;
    let img = obj.img;
    let txt = obj.txt;
    let time = obj.time;
    res.header("Access-Control-Allow-Origin","*");
    db.setinfo(`INSERT INTO IMGDESCINFO (id,type,title,img,txt,time) VALUES('${id}','${type}','${title}','${img}','${txt}','${time}')`).then((data)=>{
        if(data == "数据更新成功"){
            res.json({status:0})
        }
    },(err)=>{
        res.json({status:1})
    })

}
//单个上传图片信息(返回网络路径和文件名的对象)
exports.uploadsingleimg = (req,res)=>{
    let {buffer,mimetype} = req.file;
    let filename = (new Date().getTime())+parseInt(Math.random()*5463)+parseInt(Math.random()*7892);
    let type = mimetype.splite('/')[0];
    let path = `${mypath}/news/images/${filename}.${type}`;
    fs.writeFile(path.join(__dirname,`../public/news/images/${filename}.${type}`),buffer,'utf8',(err)=>{
        if(err){
            res.header("Access-Control-Allow-Origin","*");
            res.json(err);
        }else{
            res.header("Access-Control-Allow-Origin","*");
            res.json({'path':path,'name':`${filename}.${type}`});
        }
    })
}
//多个图片上传(用于多图预览项目)(返回网络路径和文件名的数组对象)
exports.uploadimgs = (req,res)=>{
    var arr = req.files;
    var myarr = [];
    for(var i = 0;i<arr.length;i++){
        var item = arr[i];
        let {buffer,mimetype}  = item;
        let type = mimetype.split('/')[1] 
        let filename = (new Date().getTime())+parseInt(Math.random()*7893)+parseInt(Math.random()*4562)+"."+type;
        let filepath = `${mypath}/news/images/${filename}`;
        fs.writeFileSync(path.join(__dirname,`../public/news/images/${filename}`),buffer,'utf8');
        myarr.push({'name':`${filename}`})
    }
    res.header("Access-Control-Allow-Origin","*");
    res.json(myarr);
}